<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <!--<script src="../Scripts/jquery-1.8.2.js"></script>-->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<input type="file" id="file"/>
<button id="upload">上传</button>
</body>
<script>
    var page = {
        init: function () {
            $("#upload").click($.proxy(this.upload, this));
        },

        upload: function () {
            var file = $("#file")[0].files[0],  //文件对象
                name = file.name,        //文件名
                size = file.size,        //总大小
                succeed = 0;

            // var shardSize = 4 * 1024 * 1024,    //以4MB为一个分片
            var shardSize = 20 * 1024 * 1024,    //以8MB为一个分片
                shardCount = Math.ceil(size / shardSize);  //总片数

            for (var i = 0; i < shardCount; ++i) {
                //计算每一片的起始与结束位置
                var start = i * shardSize,
                    end = Math.min(size, start + shardSize);
                //构造一个表单，FormData是HTML5新增的
                var form = new FormData();
                form.append("data", file.slice(start, end));  //slice方法用于切出文件的一部分
                form.append("name", name);
                form.append("total", shardCount);  //总片数
                form.append("index", i + 1);        //当前是第几片

                //Ajax提交
                $.ajax({
                    url: "/upload/test",
                    type: "POST",
                    data: form,
                    async: true,        //异步
                    processData: false,  //jquery不要对form进行处理
                    contentType: false,  //指定为false才能形成正确的Content-Type
                    success: function () {
                        //成功后的事件
                        succeed++;
                        if (succeed == shardCount && shardCount != 1) {
                            merge(name, shardCount);
                        }
                    }
                });
            }
        }


    };

    function merge(name, shardCount) {
        $.ajax({
            url: "/upload/merge/" + name + "/" + shardCount,
            type: "get",
            success: function () {

            }
        });
    }

    $(function () {
        page.init(); //初始化
    });

</script>
</html>